import { Util } from '../../utils/util.js';

export class MerchantPackageAuthAccount {
    constructor({ startTime, endTime, count }) {
        this.startTime = startTime ? new Date(startTime) : new Date();
        this.endTime = endTime ? new Date(endTime) : new Date();
        this.count = typeof count === 'number' ? count : 1;
        this.selected = false; // for UI
    }

    static clone(data) {
        return new MerchantPackageAuthAccount({
            startTime: new Date(data.startTime),
            endTime: new Date(data.endTime),
            count: data.count
        });
    }

    subtractCount(value) {
        this.count -= value;
        if (this.count < 1) {
            this.count = 1;
        }
    }

    addCount(value) {
        this.count += value;
        if (this.count < 1) {
            this.count = 1;
        }
    }

    static fromJson(json) {
        return new MerchantPackageAuthAccount({
            startTime: json.startTime,
            endTime: json.endTime,
            count: Util.jsonToInt(json.count)
        });
    }

    toJson() {
        return {
            startTime: this.startTime.toISOString(),
            endTime: this.endTime.toISOString(),
            count: this.count
        };
    }

    static getAccountList(jsonStr) {
        let jsonObj;
        try {
            jsonObj = JSON.parse(jsonStr);
        } catch (e) {
            jsonObj = [];
        }
        return Array.isArray(jsonObj)
            ? jsonObj.map((item) => MerchantPackageAuthAccount.fromJson(item))
            : [];
    }

    static accountListToJson(accountList) {
        return accountList.map((account) => account.toJson());
    }

    static accountListJsonString(accountList) {
        return JSON.stringify(MerchantPackageAuthAccount.accountListToJson(accountList));
    }
}
